import * as crypto from 'crypto';
import moment from 'moment-es6';

class Business {
    sleep(timeout) {
        return new Promise(resolve => {
            setTimeout(resolve, timeout);
        });
    }

    getNow() {
        return moment().unix();
    }

    getNowAfterHour(hour) {
        return moment().add(hour, 'h').unix();
    }

    getNowAfterDay(day) {
        return moment().add(day, 'd').unix();
    }

    getNowString() {
        return moment().format('YYYY-MM-DD HH:mm:ss');
    }

    md5(str) {
        return crypto.createHash('md5').update(str, 'utf8').digest('hex');
    }

    toQueryString(obj) {
        return Object.keys(obj)
            .filter(key => key !== 'sign' && obj[key] !== undefined && obj[key] !== '')
            .sort()
            .map(key => key + '=' + obj[key])
            .join('&');
    }

    makeSign(params, apiSecret) {
        let str = 'api_secret=' + apiSecret + '&' + this.toQueryString(params) + '&' + 'api_secret=' + apiSecret;
        return this.md5(str).toUpperCase();
    }

    generateRandom(length = 16) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let noceStr = '', maxPos = chars.length;
        while (length--) noceStr += chars[(Math.random() * maxPos) | 0];
        return noceStr;
    }
}

export default new Business();

